package com.javatest.h2server;

import com.javatest.dao.DaoBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/16 10:19
 */
public class InitH2DB {
    private static final Logger LOGGER = LoggerFactory.getLogger(InitH2DB.class);

    public static void init() {
        String file = getInitFile();
        if (file == null || file.isEmpty()) {
            LOGGER.warn("Can't get h2 init file!");
            return;
        }
        try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(file);
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))
        ) {
            String str;
            StringBuilder sql = new StringBuilder();
            DaoBase base = new DaoBase();
            while ((str = reader.readLine()) != null) {
                // 解决sql语句格式化成多行的问题
                // sql语句必须以:结尾
                if (str.endsWith(";")) {
                    sql.append(str);
                    base.update(sql.toString());
                    LOGGER.info("[Init db] " + sql);
                    sql.delete(0, sql.length());
                } else {
                    sql.append(str);
                }
            }
        } catch (IOException e) {
            LOGGER.error("Init h2 db error.", e);
        }
    }

    private static String getInitFile() {
        String file = null;
        try (InputStream inputStream = InitH2DB.class.getClassLoader().getResourceAsStream("dataSourceCfg.properties")) {
            Properties properties = new Properties();
            properties.load(inputStream);
            file = properties.getProperty("initfile");
        } catch (IOException e) {
            LOGGER.error("Get h2 init file error", e);
        }
        return file;
    }
}
